package com.sss.support.poi;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @author PraditR
 *
 */
public class ExcelReader <T> {
	
	private static final Logger log = LoggerFactory.getLogger(ExcelReader.class);
	private Workbook workbook;
	
	public  List<T> readTo (InputStream xcel, ReaderRole role,ModelCreator<T> creator) throws Exception {
		try {
			workbook = new HSSFWorkbook(xcel);
			
			Sheet sheet = workbook.getSheetAt(role.getSheetNo());
			log.debug("[read excel sheet name :: {}]",sheet.getSheetName());
			
			
			if(role.getStartRow() > role.getEndRow()){
				throw new IllegalArgumentException("[ start row greater than end row ]");
			}
			
			log.debug("[captured range row between :: {} - {}]",role.getStartRow(),role.getEndRow());
			List<T> models = new ArrayList<T>();
			int endrow = role.getEndRow();
			for(int i = role.getStartRow();i < endrow;i++){				
				Row r = sheet.getRow(i);
				if(r == null){
					log.warn("[The Row no. {} is null.]",i);					
				} else{
					log.debug("[row value is {}]",CellValueUtil.toStringValue(r.getCell(0)));					
					T t = creator.create(r);
					if(t != null){
						models.add(t);
					}
				}
								
			}
			return models;
		} catch (IOException io) {						
			log.error(io.getMessage(),io);
			throw io;
		} catch (Exception e){
			log.error(e.getMessage(),e);
			throw e;
		}		
	}

}
